//
//  TJPaymentDetailController.m
//  Teleport
//
//  Created by xtjun on 2020/6/16.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJPaymentDetailController.h"
#import "TJPaymentDetailHeaderView.h"
#import "TJRoundingCornerImageView.h"
#import "UIButton+LXMImagePosition.h"
#import "TJBigImageController.h"

@interface TJPaymentDetailController ()


@property (weak, nonatomic) TJPaymentDetailHeaderView *headerView;
@property (strong, nonatomic) NSDateFormatter *formatter;

@property (strong, nonatomic) UIImage *QRImage;
@property (strong, nonatomic) NSMutableArray *datas;
@end

@implementation TJPaymentDetailController {
    dispatch_source_t _timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.datas = @[].mutableCopy;
    
    _formatter = [[NSDateFormatter alloc] init];
    [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    TJPaymentDetailHeaderView *headerView = [[TJPaymentDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 226)];
    
    headerView.model = self.model;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = 98;
    self.navigationBar.alpha = 0;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.tableHeaderView = headerView;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = 60;
    [self.tableView registerClass:TJStyle1Cell.self forCellReuseIdentifier:style1Cell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.bottom.offset(0);
    }];
    _headerView = headerView;
    
    [self showCountdown];
    
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 180)];
    self.tableView.tableFooterView = footerView;
    
    UIImageView *authImageView = [UIImageView tj_addToView:footerView];
    authImageView.image = [UIImage imageNamed:@"payDetailAuthIcon"];
    [authImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(24);
        make.width.offset(120);
        make.height.offset(30);
    }];
    
    
    UILabel *textLabel = [UILabel lableWithSuperView:authImageView font:UIFont_Px(12) color:UIColor.whiteColor title:@"对方已完成认证".localizedString textAlignment:NSTextAlignmentLeft];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(2);
        make.right.offset(-8);
    }];
    
    
    TJRoundingCornerButton *QRCodeButton = [TJRoundingCornerButton roundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft radius:18];
    [QRCodeButton addTarget:self action:@selector(didClicQrCodeButton) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:QRCodeButton];
    QRCodeButton.titleLabel.font = UIFont_Px(16);
    [QRCodeButton setImage:[UIImage imageNamed:@"payDetailQRcodeIcon"] forState:UIControlStateNormal];
    [QRCodeButton setImage:[UIImage imageNamed:@"payDetailQRcodeIcon"] forState:UIControlStateHighlighted];
    QRCodeButton.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.4];
    [QRCodeButton setTitle:@"收款码".localizedString forState:UIControlStateNormal];
    [QRCodeButton setImagePosition:LXMImagePositionLeft spacing:5];
    [QRCodeButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [QRCodeButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [QRCodeButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [QRCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.centerY.equalTo(authImageView);
        make.width.offset(100);
        make.height.offset(36);
    }];
    
    UIButton *completeButton = [UIButton buttonWithSuperView:footerView font:UIFont_Px(16) color:UIColor.whiteColor title:@"我已付款成功".localizedString];
    completeButton.backgroundColor = UIColor.tj_mainColor;
    [completeButton addTarget:self action:@selector(didClickCompleteButton) forControlEvents:UIControlEventTouchUpInside];
    [completeButton shearRoundedCornersWithRadiu:3];
    [completeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.left.offset(16);
        make.height.offset(44);
        make.centerX.offset(0);
        make.top.equalTo(authImageView.mas_bottom).offset(80);
    }];
    
    TJCellStyleModel *model = [TJCellStyleModel cellStyleModelWithText:@"收款人".localizedString detailText:self.model.accModel.uname cellClass:@"TJStyle1Cell"];
    model.attributedStringIcon = @"detall_copy_icon";
    model.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
    model.isNeedCopy = YES;
    [self.datas addObject:model];
    NSString *detext = self.model.accModel.name;
    if (self.model.accModel.bankCard.length != 0) {//银行卡
        detext = self.model.accModel.bankCard;
    }
    
    TJCellStyleModel *model1 = [TJCellStyleModel cellStyleModelWithText:self.model.accModel.text detailText:detext cellClass:@"TJStyle1Cell"];
    
    model1.attributedStringIcon = @"detall_copy_icon";
    model1.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
    model1.isNeedCopy = YES;
    [self.datas addObject:model1];
    
    if (self.model.accModel.bankCard.length != 0) {//银行卡
        
        
        //影藏二维码
        QRCodeButton.hidden = YES;
        TJCellStyleModel *model2 = [TJCellStyleModel cellStyleModelWithText:@"开户银行" detailText:self.model.accModel.bankName cellClass:@"TJStyle1Cell"];
        model2.attributedStringIcon = @"detall_copy_icon";
        model2.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
        model2.isNeedCopy = YES;
        [self.datas addObject:model2];
        TJCellStyleModel *model3 = [TJCellStyleModel cellStyleModelWithText:@"开户支行" detailText:self.model.accModel.bankAddress cellClass:@"TJStyle1Cell"];
        model3.attributedStringIcon = @"detall_copy_icon";
        model3.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
        model3.isNeedCopy = YES;
        [self.datas addObject:model3];
    }
    
}

- (void)didClickCompleteButton {
    
    NSDictionary *parameters = @{
        @"priceOrderId": self.model.priceOrderId,
        @"userId": TJUserInfo.readInfo.userId,
        @"payType":self.model.payType
    };
    [self showloading];
    [TJNetworking.shareNetworking POSTNew:@"otc/order/payment" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        [self hiddenloading];
        //         if (self.countdownFinishBlock) {
        //                      self.countdownFinishBlock();
        //            }
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

- (void)didClicQrCodeButton {
    
    //    if (_QRImage) {
    //        TJBigImageController *bigImageController = [[TJBigImageController alloc] init];
    //        bigImageController.image = _QRImage;
    //        [self.navigationController pushViewController:bigImageController animated:YES];
    //        return;
    //    }
    
    
    [self showloading];
    NSString *imageUrl = self.model.accModel.url;
    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (error) return;
        self.QRImage = image;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hiddenloading];
            TJBigImageController *bigImageController = [[TJBigImageController alloc] init];
            bigImageController.image = image;
            [self.navigationController pushViewController:bigImageController animated:YES];
        });
        
    }];
    
    
}

- (void)showCountdown {
    
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    
    
    if (self.model.orderEndTime <= self.model.nowTime) {
        self.headerView.stateLabel.hidden = YES;
        return;
    };//大于倒计时时间
    
    __block NSInteger timestamp = (self.model.orderEndTime - self.model.nowTime)/1000;//倒计时s数
    self.headerView.stateLabel.hidden = NO;
    
    if (timestamp < 0) return;
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                //                if (self.countdownFinishBlock) {
                //                    self.countdownFinishBlock();
                //                }
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            
            NSString *countdownValue = [Tools videoLengthWithSeconds:timestamp];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (self.model.status == 3 && [self.model.userId isEqualToString:TJUserInfo.readInfo.userId]) {//待买家付款
                    NSString *stateStr = [NSString stringWithFormat:@"%@%@", @"待付剩余时间".localizedString, countdownValue];
                    CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
                    [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.offset(W);
                    }];
                    self.headerView.stateLabel.text = stateStr;
                }
                
                
                //                NSLog(@"timestamp = %ld",(long)timestamp);
                //                NSLog((@"剩余时间:%@".localizedString), self.headerView.stateLabel.text);
            });
        }
    });
    _timer = timer;
    dispatch_resume(timer);
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJStyle1Cell *cell = [tableView dequeueReusableCellWithIdentifier:style1Cell forIndexPath:indexPath];
    TJCellStyleModel *model = self.datas[indexPath.row];
    cell.model = model;
    cell.tj_textLabel.textColor = UIColor_Hex(0x656565);
    cell.tj_textLabel.font = UIFont_Px(15);
    cell.selectionStyle = model.isNeedCopy ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
    cell.tj_detailTextLabel.font = MediumFont(15);
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TJCellStyleModel *model = self.datas[indexPath.row];
    
    if (model.isNeedCopy) {
        [Tools copyStringToPasteboard:model.detailText.replacingEmptyString];
        return;
    }
}


//- (void)viewDidDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    
////    if (_viewDidDisappearhBlock) {
////        _viewDidDisappearhBlock();
////    }
//    if (_timer) {
//        dispatch_source_cancel(_timer);
//    }
//}

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}


@end


@implementation TJPaymentDetailModel
+ (instancetype)paymentDetailModelWithTotalPrice:(NSString *)totalPrice orderEndTime:(NSInteger)orderEndTime nowTime:(NSInteger)nowTime payType:(NSString *)payType account:(TJCellStyleModel *)accModel priceOrderId:(NSString *)priceOrderId status:(NSInteger)status userId:(NSString *)userId;{
    TJPaymentDetailModel *model = [[TJPaymentDetailModel alloc] init];
    model.totalPrice = totalPrice;
    model.orderEndTime = orderEndTime;
    model.nowTime = nowTime;
    model.payType = payType;
    model.accModel = accModel;
    model.priceOrderId = priceOrderId;
    model.status = status;
    model.userId = userId;
    return model;
}
@end
